package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.logging.Logger;
/**
 * 用户认证控制器 - 处理注册、登录等前端用户功能
 */
@Controller
@RequestMapping("/auth")
public class UserAuthController {

    @Autowired
    private UserService userService;
    
    private static final Logger logger = Logger.getLogger(UserAuthController.class.getName());

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String showLoginPage() {
        return "frontend/login";
    }

    /**
     * 显示注册页面
     */
    @GetMapping("/register")
    public String showRegisterPage() {
        return "frontend/register";
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public String register(@RequestParam("phone") String phone,
                          @RequestParam("password") String password,
                          @RequestParam("confirmPassword") String confirmPassword,
                          @RequestParam("username") String username,
                          @RequestParam(required = false, value = "email") String email,
                          @RequestParam(required = false, value = "realName") String realName,
                          @RequestParam(defaultValue = "0", value = "sex") Integer sex,
                          @RequestParam(required = false, value = "birthday") String birthday,
                          Model model,
                          HttpSession session) {
        try {
            // 验证密码一致性
            if (!password.equals(confirmPassword)) {
                model.addAttribute("error", "两次输入的密码不一致");
            return "frontend/register";
            }
            
            // 验证手机号格式
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                model.addAttribute("error", "手机号格式不正确");
            return "frontend/register";
            }
            
            // 验证用户名长度
            if (username.length() < 2 || username.length() > 20) {
                model.addAttribute("error", "用户名长度应在2-20个字符之间");
            return "frontend/register";
            }
            
            // 验证密码长度
            if (password.length() < 6 || password.length() > 20) {
                model.addAttribute("error", "密码长度应在6-20个字符之间");
            return "frontend/register";
            }
            
            // 密码强度验证由前端处理，后端保留基本长度验证
            
            // 验证邮箱格式（如果提供了）
            if (email != null && !email.isEmpty() && !email.matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")) {
                model.addAttribute("error", "邮箱格式不正确");
            return "frontend/register";
            }
            
            // 验证真实姓名（如果提供了）
            if (realName != null && !realName.isEmpty() && (realName.length() < 2 || realName.length() > 20)) {
                model.addAttribute("error", "真实姓名长度应在2-20个字符之间");
            return "frontend/register";
            }

            // 验证用户名是否已存在
            User existingByUsername = userService.findByUserName(username);
            if (existingByUsername != null) {
                model.addAttribute("error", "用户名已存在");
            return "frontend/register";
            }
            
            // 验证手机号是否已存在
            User existingByPhone = userService.findByPhone(phone);
            if (existingByPhone != null) {
                model.addAttribute("error", "手机号已存在");
            return "frontend/register";
            }

            // 创建新用户
            User user = new User();
            user.setPhone(phone);
            user.setPassword(password); // setPassword方法会同时设置password和userpwd
            user.setUsername(username);
            user.setEmail(email);
            user.setRealName(realName);
            user.setSex(sex);
            user.setBirthday(birthday);
            user.setType(1); // 普通用户
            user.setStatus(0); // 启用状态
            user.setCreateTime(LocalDateTime.now().toString());
            
            logger.info("Creating new user with phone: " + phone + ", username: " + username);

            try {
                userService.add(user);
            } catch (Exception e) {
                logger.severe("Registration error for user " + username + ": " + e.getMessage());
                model.addAttribute("error", "注册失败，请稍后重试");
            return "frontend/register";
            }
            // 注册成功，设置Session实现自动登录
            session.setAttribute("loginUser", user);
            logger.info("User registered and automatically logged in: " + user.getUsername() + " (ID: " + user.getUserid() + ")");
            // 重定向到完善个人信息页面
            return "redirect:/auth/profile-edit";
        } catch (Exception e) {
            logger.severe("Registration error for phone " + phone + ": " + e.getMessage());
            model.addAttribute("error", "注册失败：" + e.getMessage());
            return "frontend/register";
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public String login(@RequestParam("phone") String phone,
                       @RequestParam("password") String password,
                       HttpSession session,
                       Model model) {
        try {
            // 验证手机号格式
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                model.addAttribute("error", "手机号格式不正确");
                return "frontend/login";
            }
            
            // 查询用户
            User user = userService.findByPhone(phone);
            
            // 验证用户是否存在和密码是否正确
              boolean passwordMatch = false;
              if (user != null) {
                // 直接比较密码
                passwordMatch = user.getPassword().equals(password);
                if (passwordMatch) {
                    // 密码验证通过
                    logger.info("User password verified: " + phone);
                }
              }
            
            if (user == null || !passwordMatch) {
                model.addAttribute("error", "手机号或密码不正确");
                return "frontend/login";
            }
            
            // 验证用户状态
            if (user.getStatus() != 0) {
                model.addAttribute("error", "账号已被禁用，请联系管理员");
                return "frontend/login";
            }
            
            // 保存用户到Session
            session.setAttribute("loginUser", user);
            logger.info("User logged in: " + user.getUsername() + " (ID: " + user.getUserid() + ")");
            // 更新成功后跳转到患者首页
            return "redirect:/frontend/patient-index";
        } catch (Exception e) {
            model.addAttribute("error", "登录失败：" + e.getMessage());
            return "frontend/login";
        }
    }

    /**
     * 用户登出
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        session.invalidate(); // 销毁session以确保安全
        return "redirect:/auth/login";
    }
    
    /**
     * 显示完善个人信息页面
     */
    @GetMapping("/profile-edit")
    public String showProfileEdit(HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            model.addAttribute("error", "请先登录");
            return "redirect:/auth/login";
        }
        
        // 确保返回的是完整的用户信息
        User user = userService.findById(loginUser.getUserid());
        session.setAttribute("loginUser", user);
        
        return "frontend/profile-edit";
    }
    
    /**
     * 更新用户个人信息
     */
    @PostMapping("/updateProfile")
    public String updateProfile(Integer userId, String realName, String idcard, Integer sex,
                              String birthday, String email, HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !loginUser.getUserid().equals(userId)) {
            model.addAttribute("error", "用户验证失败");
            return "redirect:/auth/login";
        }
        
        try {
            // 验证必填字段
            if (realName == null || realName.isEmpty()) {
                model.addAttribute("error", "真实姓名不能为空");
                return "frontend/profile-edit";
            }
            
            if (idcard == null || idcard.isEmpty()) {
                model.addAttribute("error", "身份证号不能为空");
                return "frontend/profile-edit";
            }
            
            if (sex == null || sex == 0) {
                model.addAttribute("error", "请选择性别");
                return "frontend/profile-edit";
            }
            
            if (birthday == null || birthday.isEmpty()) {
                model.addAttribute("error", "出生日期不能为空");
                return "frontend/profile-edit";
            }
            
            // 更新用户信息
            User user = new User();
            user.setUserid(Long.valueOf(userId));
            user.setRealName(realName);
            user.setIdcard(idcard);
            user.setSex(sex);
            user.setBirthday(birthday);
            user.setEmail(email);
            
            // 更新用户信息
            userService.modify(user);
            
            // 更新session中的用户信息
            loginUser = userService.findById(Long.valueOf(userId));
            session.setAttribute("loginUser", loginUser);
            
            // 更新成功后跳转到患者首页
            model.addAttribute("success", "个人信息更新成功");
            return "redirect:/frontend/patient-index";
            
        } catch (Exception e) {
            logger.severe("Update profile error for user " + userId + ": " + e.getMessage());
            model.addAttribute("error", "更新过程中发生错误，请稍后重试");
            return "frontend/profile-edit";
        }
    }
}
